﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using WinBookKeeping.Models;
using WinBookKeeping.Utility;

namespace WinBookKeeping
{
    public partial class FrmMonthStatisics : Form
    {
        private const decimal ABNORMAL_THRESHOLD = 1.5M; // 异常消费阈值（平均值的1.5倍）
        private const decimal SAVING_THRESHOLD = 0.8M;   // 节约阈值（平均值的0.8倍）
        private const int TREND_MONTHS = 6;              // 趋势分析月数

        public FrmMonthStatisics()
        {
            InitializeComponent();
        }

        //本月收入 支出 收支
        decimal thisMonthIn = 0.00M,
                thisMonthEx = 0.00M,
                thisMonthInEx = 0.00M;
        //总收支列表
        List<RecordInfo> recordList = new List<RecordInfo>();
        //月统计数据列表
        List<MonthStatInfo> monthStatList = new List<MonthStatInfo>();

        private async void FrmMonthStatisics_Load(object sender, EventArgs e)
        {
            //按月统计数据
            await StatisticsData();
            //分析消费行为
            AnalyzeConsumptionBehavior();
        }

        private async Task StatisticsData()
        {
            lvInExDataList.Items.Clear();
            //加载所有收支记录
            await LoadAllRecordList();
            //按月统计收支数据并加载列表
            StatisticsMonthList();
            //加载本月收支数据
            LoadStatInfo();
        }

        private async Task LoadAllRecordList()
        {
            //重置
            thisMonthIn = 0.00M;
            thisMonthEx = 0.00M;
            thisMonthInEx = 0.00M;
            recordList = await CommonHelper.GetAllRecordList();
        }

        private void StatisticsMonthList()
        {
            monthStatList.Clear();
            //筛选出日期列表
            List<string> ListDate = recordList.Select(r => r.RecordTime.ToString("yyyy-MM-dd")).Distinct().ToList();
            //获取年份列表
            List<int> years = ListDate.Select(d => DateTime.Parse(d).Year).Distinct().ToList();
            //本月月份
            int thisMonth = DateTime.Now.Month;
            //按年 月统计
            foreach (int year in years)
            {
                //获取该年份所有月份
                List<int> yearMonths = ListDate.Where(d => DateTime.Parse(d).Year == year).Select(d => DateTime.Parse(d).Month).Distinct().ToList();
                //当前年份所有的收支记录
                var yrecordList = recordList.Where(r => r.RecordTime.Year == year);
                foreach (int month in yearMonths)
                {
                    decimal monthinTotal = 0.00M,
                            monthexTotal = 0.00M,
                            monthinexTotal = 0.00M;
                    //当前月份的收支记录
                    var mrecordList = yrecordList.Where(r => r.RecordTime.Month == month);
                    foreach (var record in mrecordList)
                    {
                        if (record.ItemType == "收入")
                            monthinTotal += record.Money;
                        else
                            monthexTotal += record.Money;
                    }
                    monthinexTotal = monthinTotal - monthexTotal;
                    //本月收入 支出 收支数据
                    if (month == thisMonth)
                    {
                        thisMonthIn = monthinTotal;
                        thisMonthEx = monthexTotal;
                        thisMonthInEx = monthinexTotal;
                    }
                    MonthStatInfo monthInfo = new MonthStatInfo()
                    {
                        Year = year.ToString(),
                        Month = month.ToString(),
                        InTotal = monthinTotal,
                        ExTotal = monthexTotal,
                        InExTotal = monthinexTotal
                    };
                    monthStatList.Add(monthInfo);
                }
            }
            //统计列表加载
            if (monthStatList.Count > 0)
            {
                foreach (MonthStatInfo item in monthStatList)
                {
                    ListViewItem li = new ListViewItem();
                    li.Text = item.Year;
                    li.SubItems.Add(item.Month);
                    li.SubItems.Add("￥" + item.InTotal.ToString("0.00"));
                    li.SubItems.Add("￥" + item.ExTotal.ToString("0.00"));
                    li.SubItems.Add("￥" + item.InExTotal.ToString("0.00"));
                    lvInExDataList.Items.Add(li);
                }
            }
        }

        private void LoadStatInfo()
        {
            lblTMonthIn.Text = "￥" + thisMonthIn.ToString("0.00") + " 元";
            lblTMonthEx.Text = "￥" + thisMonthEx.ToString("0.00") + " 元";
            lblTMonthInEx.Text = "￥" + thisMonthInEx.ToString("0.00") + " 元";
        }

        //重新统计
        private void btnStatistic_Click(object sender, EventArgs e)
        {
            StatisticsData();
            AnalyzeConsumptionBehavior();
        }

        //分析消费行为
        private void AnalyzeConsumptionBehavior()
        {
            if (monthStatList.Count == 0) return;

            var analysis = new StringBuilder();

            // 1. 计算平均月支出
            decimal avgMonthlyExpense = monthStatList.Average(d => d.ExTotal);

            // 2. 分析本月支出
            if (thisMonthEx > avgMonthlyExpense * ABNORMAL_THRESHOLD)
            {
                analysis.AppendLine($"⚠️ 本月支出（￥{thisMonthEx:0.00}）显著高于平均月支出（￥{avgMonthlyExpense:0.00}），建议控制支出。");
            }
            else if (thisMonthEx < avgMonthlyExpense * SAVING_THRESHOLD)
            {
                analysis.AppendLine($"✅ 本月支出（￥{thisMonthEx:0.00}）低于平均月支出（￥{avgMonthlyExpense:0.00}），继续保持！");
            }

            // 3. 分析消费趋势
            var recentMonths = monthStatList.OrderByDescending(d => d.Year + d.Month).Take(TREND_MONTHS).ToList();
            if (recentMonths.Count >= 3)
            {
                var trend = AnalyzeTrend(recentMonths);
                analysis.AppendLine(trend);
            }

            // 4. 分析异常消费
            var abnormalMonths = monthStatList.Where(d => d.ExTotal > avgMonthlyExpense * ABNORMAL_THRESHOLD).ToList();
            if (abnormalMonths.Any())
            {
                analysis.AppendLine("\n📊 异常消费提醒：");
                foreach (var month in abnormalMonths)
                {
                    analysis.AppendLine($"• {month.Year}年{month.Month}月 支出 ￥{month.ExTotal:0.00}，超出平均月支出 {((month.ExTotal / avgMonthlyExpense - 1) * 100):0.0}%");
                }
            }

            // 5. 生成节约建议
            analysis.AppendLine("\n💡 节约建议：");
            if (thisMonthEx > avgMonthlyExpense)
            {
                analysis.AppendLine($"• 本月支出较高，建议减少非必要支出");
            }
            if (monthStatList.Count >= 3)
            {
                var quarterlyAvg = monthStatList.TakeLast(3).Average(d => d.ExTotal);
                if (quarterlyAvg > avgMonthlyExpense)
                {
                    analysis.AppendLine($"• 近三个月平均月支出（￥{quarterlyAvg:0.00}）高于历史平均，建议控制日常开销");
                }
            }

            // 6. 收入支出比分析
            if (thisMonthIn > 0)
            {
                decimal incomeExpenseRatio = thisMonthEx / thisMonthIn;
                if (incomeExpenseRatio > 0.8M)
                {
                    analysis.AppendLine($"• 本月支出占收入比例较高（{incomeExpenseRatio:P0}），建议适当控制支出");
                }
            }

            // 7. 季节性分析
            var seasonalAnalysis = AnalyzeSeasonalPattern();
            if (!string.IsNullOrEmpty(seasonalAnalysis))
            {
                analysis.AppendLine("\n🌡️ 季节性分析：");
                analysis.AppendLine(seasonalAnalysis);
            }

            // 显示分析结果
            txtAnalysis.Text = analysis.ToString();
        }

        private string AnalyzeTrend(List<MonthStatInfo> recentMonths)
        {
            var trend = new StringBuilder();
            trend.AppendLine("\n📈 消费趋势分析：");

            // 计算趋势
            var expenses = recentMonths.Select(d => d.ExTotal).ToList();
            bool isIncreasing = true;
            bool isDecreasing = true;

            for (int i = 1; i < expenses.Count; i++)
            {
                if (expenses[i] <= expenses[i - 1]) isIncreasing = false;
                if (expenses[i] >= expenses[i - 1]) isDecreasing = false;
            }

            if (isIncreasing)
            {
                trend.AppendLine("• 近期支出呈上升趋势，请注意控制支出");
            }
            else if (isDecreasing)
            {
                trend.AppendLine("• 近期支出呈下降趋势，继续保持！");
            }
            else
            {
                trend.AppendLine("• 近期支出波动较大，建议保持稳定消费习惯");
            }

            // 计算波动率
            decimal maxExpense = expenses.Max();
            decimal minExpense = expenses.Min();
            decimal volatility = (maxExpense - minExpense) / minExpense;

            if (volatility > 0.5M)
            {
                trend.AppendLine($"• 支出波动较大（波动率 {volatility:P0}），建议保持稳定消费习惯");
            }

            return trend.ToString();
        }

        private string AnalyzeSeasonalPattern()
        {
            if (monthStatList.Count < 12) return string.Empty;

            var analysis = new StringBuilder();
            var currentMonth = DateTime.Now.Month;
            var lastYearSameMonth = monthStatList.FirstOrDefault(m =>
                m.Year == (DateTime.Now.Year - 1).ToString() &&
                m.Month == currentMonth.ToString());

            if (lastYearSameMonth != null)
            {
                decimal yearOverYearChange = (thisMonthEx - lastYearSameMonth.ExTotal) / lastYearSameMonth.ExTotal;
                if (Math.Abs(yearOverYearChange) > 0.2M)
                {
                    analysis.AppendLine($"• 与去年同期相比，支出{(yearOverYearChange > 0 ? "增加" : "减少")}了 {Math.Abs(yearOverYearChange):P0}");
                }
            }

            // 分析季节性波动
            var monthlyAverages = monthStatList
                .GroupBy(m => int.Parse(m.Month))
                .Select(g => new { Month = g.Key, AvgExpense = g.Average(m => m.ExTotal) })
                .OrderBy(x => x.Month)
                .ToList();

            if (monthlyAverages.Count >= 12)
            {
                var highestMonth = monthlyAverages.OrderByDescending(x => x.AvgExpense).First();
                var lowestMonth = monthlyAverages.OrderBy(x => x.AvgExpense).First();

                analysis.AppendLine($"• 支出最高的月份是{highestMonth.Month}月，平均支出 ￥{highestMonth.AvgExpense:0.00}");
                analysis.AppendLine($"• 支出最低的月份是{lowestMonth.Month}月，平均支出 ￥{lowestMonth.AvgExpense:0.00}");
            }

            return analysis.ToString();
        }

        private void lblTMonthEx_Click(object sender, EventArgs e)
        {

        }
    }
}
